package com.banciyuan.bcywebview.biz.main.daily;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;

import java.util.List;

/**
 * Created by hy on 2016/5/3.
 */
public abstract class RankTagViewProcessor {
    private LinearLayout[] tagContainers;
    private LayoutInflater mLayoutInflater;
    private List data;

    public RankTagViewProcessor(LayoutInflater layoutInflater, List data, LinearLayout... tagContainers) {
        this.tagContainers = tagContainers;
        mLayoutInflater = layoutInflater;
        this.data = data;
        init();
    }

    private void init() {
        for (LinearLayout tagContainer : tagContainers) {
            tagContainer.removeAllViews();
        }
    }

    public void addTag(int baseNum, int layoutId, TextView[]... args) {
        if (args.length != tagContainers.length)
            return;
        for (int i = 0; i < args.length; i++) {
            addTag(baseNum, layoutId, args[i], tagContainers[i]);
            initInterestTagClickLisener(args[i]);
        }
    }

    public void addTag(int baseNum, int layoutId, TextView[] tagArray, ViewGroup tagContainer) {
        int lineCount = data.size() % baseNum == 0 ? data.size() / baseNum : data.size() / baseNum + 1;
        for (int i = 0; i < lineCount; i++) {
            LinearLayout viewLine = (LinearLayout) mLayoutInflater.inflate(R.layout.base_tag_line, tagContainer, false);
            for (int j = i * baseNum; j < (i + 1) * baseNum; j++) {
                initTagView(viewLine, j, tagArray, layoutId);
            }
            tagContainer.addView(viewLine);
        }
        initInterestTagClickLisener(tagArray);
    }

    private void initTagView(LinearLayout viewLine, int i, TextView[] tagArray, int layoutId) {
        final TextView viewTag = (TextView) mLayoutInflater.inflate(layoutId, viewLine, false);
        if (i < data.size()) {
            final String tagName = getTagName(i, viewTag);
            viewTag.setText(tagName);
            tagArray[i] = viewTag;
        } else {
            viewTag.setVisibility(View.INVISIBLE);
        }
        viewLine.addView(viewTag);
    }

    private void initInterestTagClickLisener(TextView[] tagArray) {
        for (int i = 0; i < data.size(); i++) {
            final int finalI = i;
            tagArray[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onTagClick(finalI);
                }
            });
        }
    }

    public abstract String getTagName(int i, TextView textView);

    public abstract void onTagClick(int i);
}
